package gallery

import (
	pb "ReferenceMonitor/sdk/rpc/pb_gen"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"io"
	"io/ioutil"
	"time"
)

type ClientOpt struct {
	Addr     string
	duration time.Duration
}

type ClientRPC struct {
	//pb.GalleryClient
	opt    ClientOpt
	conn   *grpc.ClientConn
	client pb.GalleryClient
}

func NewClientRPC(opt ClientOpt) *ClientRPC {
	conn, err := grpc.Dial(opt.Addr, grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		fmt.Println("Connect failed", err)
		return nil
	}
	client := pb.NewGalleryClient(conn)
	//client.Version()
	return &ClientRPC{
		opt:    opt,
		conn:   conn,
		client: client,
	}
}

func (c *ClientRPC) RpcVersion() string {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	r, _ := c.client.Version(ctx, &pb.String{})
	return r.Content
}

func (c *ClientRPC) RpcPictureList() []string {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	var ret []string
	r, err := c.client.GetPictureList(ctx, &pb.PictureRequest{})
	if err != nil {
		fmt.Println("Failed to Get Pictures: ", err)
		return ret
	}

	for _, pic := range r.Pictures {
		ret = append(ret, pic.Path)
	}
	return ret
}

func (c *ClientRPC) DownloadPicture(gallery, path string, savePath string) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()

	downClient, err := c.client.Download(ctx, &pb.PictureRequest{
		Uid:     1,
		Gallery: gallery,
		Path:    path,
	})

	if err != nil {
		fmt.Println("Failed to Call API DownloadPicture: ", err)
		return err
	}

	bytes := make([]byte, 0)

	for {
		chunk, err := downClient.Recv()
		fmt.Println(chunk)
		if err == io.EOF {
			//stream.S
			break
		} else if err != nil {
			fmt.Println("Failed to Recv File: ", err)
			return err
		}
		//fmt.Println(chunk)
		bytes = append(bytes, chunk.Content...)
	}
	err = ioutil.WriteFile(savePath, bytes, 0644)
	return err
}

func (c *ClientRPC) Close() {
	c.conn.Close()
}
